//
//  AllProductTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/28.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "FunctionVC.h"
#import "FunctionHeadView.h"
#import "FunctionDemandTabVC.h"
#import "FunctionServiceTabVC.h"
#import "DemandCell.h"
#import "ServiceCell.h"
#import "HomeModel.h"
#import "ServiceModel.h"
#import "SubjectRecommendModel.h"
#import "FunctionDemandTabVC.h"
#import "DemandTheHallContentVC.h"
#import "ServiceContentTabVC.h"
@interface FunctionVC ()<UITableViewDelegate,UITableViewDataSource,FunctionHeadViewDelegate,DemandCellDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate,FunctionDemandTabVCDelegate>
@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) FunctionHeadView *headView;
@property(nonatomic,strong) FunctionDemandTabVC *demandVC;
@property(nonatomic,strong) FunctionServiceTabVC *serviceVC;
@property(nonatomic,strong) NSMutableArray *demandArray;
@property(nonatomic,strong) NSMutableArray *serviceArray;
@property(nonatomic,strong) NSMutableArray *dataMuta;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,assign) NSInteger pageNum;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) UIButton *checkBtn;
@property(nonatomic,strong) MJRefreshAutoNormalFooter *footer;
@end

@implementation FunctionVC
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 10, kVWidth, kVHeight-CGRectGetMaxY(self.headView.frame)-kNavAndStatusHight) style:UITableViewStylePlain];
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
        _tableView.mj_header = header;
        [header beginRefreshing];
        self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
        self.tableView.mj_footer = self.footer;
                [self.footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
 forState:MJRefreshStateNoMoreData];
                self.footer.stateLabel.font = [UIFont systemFontOfSize:12];
                self.footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
-(NSMutableArray *)dataMuta
{
    if (!_dataMuta) {
        _dataMuta = [NSMutableArray array];
    }
    return _dataMuta;
}
-(NSMutableArray *)demandArray
{
    if (!_demandArray) {
        _demandArray = [NSMutableArray array];
        
    }
    return _demandArray;
}
-(NSMutableArray *)serviceArray
{
    if (!_serviceArray) {
        _serviceArray = [NSMutableArray array];
        
    }
    return _serviceArray;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:NO];
    NSNotification *notification = [NSNotification notificationWithName:@"hiddenMenuView" object:nil];
    [[NSNotificationCenter defaultCenter]postNotification:notification];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [AFHTTPSessionManager manager];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.headView = [[FunctionHeadView alloc]initWithFrame:CGRectMake(0, 0, kUIScreen.size.width, 45)];
    self.headView.delegate = self;
    [self.view addSubview:self.headView];
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headView.frame), kVWidth, kVHeight-CGRectGetMaxY(self.headView.frame))];
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.tableView];
    self.pageNum = 1;
    self.pageSize = arc4random() % 3+3;
    self.scrollView.contentSize = CGSizeMake(kVWidth*3, 0);
    __weak typeof (self)weakSelf = self;
    self.demandVC = [[FunctionDemandTabVC alloc]init];
    self.demandVC.delegate = self;
    self.demandVC.subjectModel = self.subjectModel;
    self.demandVC.navHeight = kNavAndStatusHight+kStatusBarHeight*2;
    self.demandVC.view.frame = CGRectMake(kVWidth, 0, kVWidth, kVHeight-10);
    [self.scrollView addSubview:self.demandVC.view];
    
    self.serviceVC = [[FunctionServiceTabVC alloc]init];
    self.serviceVC.returnValueBlock = ^(ServiceModel * _Nonnull model) {
        ServiceContentTabVC *vc = [[ServiceContentTabVC alloc]init];
        vc.model = model;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    self.serviceVC.navHeight = kNavAndStatusHight+kStatusBarHeight*2;
    self.serviceVC.view.frame = CGRectMake(kVWidth*2, 0, kVWidth, kVHeight);
    self.serviceVC.subjectModel = self.subjectModel;
    [self.scrollView addSubview:self.serviceVC.view];
    
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkTokenFunction:) name:@"checkTokenFunction" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkTokenError:) name:@"checkTokenError" object:nil];
//     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeInternet:) name:@"changeInternet" object:nil];
}
#pragma mark-代理:FunctionDemandTabVCDelegate---点击跳转到需求详情
-(void)functionDemandTabVC:(FunctionDemandTabVC *)functionDemandTabVC withIndexPath:(NSIndexPath *)indexPath withModel:(HomeModel *)model
{
    DemandTheHallContentVC *vc = [[DemandTheHallContentVC alloc]init];
    vc.homeModel = model;
    vc.returnValueBlock = ^(NSInteger selected) {
        model.collectStatus = selected;
        [functionDemandTabVC.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)refresh
{
    self.pageNum  = 1;
    self.demandArray = nil;
    self.serviceArray = nil;
    self.dataMuta = nil;
    [self.tableView.mj_footer endRefreshing];
    [self reloadInternetData];
}
-(void)reloadMore
{
    self.pageNum ++;
    self.pageSize = arc4random() % 3+3;
    [self reloadInternetData];
}
-(void)reloadInternetData
{
//    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
//    [WSProgressHUD show];
    NSString *pageNums = [NSString stringWithFormat:@"%ld",(long)self.pageNum];
    NSString *pageSizes = [NSString stringWithFormat:@"%ld",(long)self.pageSize];
    dispatch_group_t group =dispatch_group_create();
    dispatch_queue_t globalQueue=dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);
    dispatch_group_async(group, globalQueue, ^{
        for (int i = 0; i<2; i++) {
            if (i == 0) {//需求
                self.urlString = [NSString stringWithFormat:@"%@/demand/selectTranslateDemand",kUrl];
                self.dict = @{
                              @"pageNum":pageNums,
                              @"pageSize":pageSizes,
                              @"ass":self.subjectModel.title,
                              @"assub":@"",
                              @"uid":[UserDefaultsHelper readUid],
                              @"token":[UserDefaultsHelper readToken]
                              };

            }else{//服务
                self.urlString = [NSString stringWithFormat:@"%@/association/indexSearch",kUrl];
                self.dict = @{
                              @"page":pageNums,
                              @"rows":pageSizes,
                              @"param":self.subjectModel.title
                              };
            }
            XLog(@"self.dict:%@",self.dict);
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                XLog(@"functionresponseObject:%@",responseObject);
                NSArray *temp = [responseObject objectForKey:@"date"];
                XLog(@"temp:%@",temp);
                XLog(@"temp.count:%ld",temp.count);
                if (i == 0) {
                    if (temp.count) {
                        for (NSDictionary *dict in temp) {
                            HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
                            [self.dataMuta addObject:model];
                        }
                        [self.tableView.mj_footer endRefreshing];
                    }else {
                        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                    }
                }else {
                    if (temp.count) {
                        for (NSDictionary *dict in temp) {
                            ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
                            [self.dataMuta addObject:model];
                        }
                        [self.tableView.mj_footer endRefreshing];
                    }else {
                        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                    }
                }
                
                if (!self.dataMuta.count) {
                    XLog(@"没有数据");
                    self.tableView.emptyDataSetSource = self;
                    self.tableView.emptyDataSetDelegate = self;
                    [self.tableView.mj_footer removeFromSuperview];
                }else {
                }
                dispatch_semaphore_signal(semaphore);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                XLog(@"error:%@",error);
                dispatch_semaphore_signal(semaphore);
                self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                [self.footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerNoInternet"]forState:MJRefreshStateNoMoreData];
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
    });
    
    dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
        XLog(@"%@---全部结束。。。",[NSThread currentThread]);
        XLog(@"self.serveMuta:%@",self.serviceArray);
        XLog(@"self.demandArray :%@",self.demandArray );
        XLog(@"dataMuta :%@",self.dataMuta );
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
            [WSProgressHUD dismiss];
        });
        
    });
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMuta.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];

    if ([self.dataMuta[indexPath.row] isKindOfClass:[HomeModel class]]) {
        DemandCell *cell = [DemandCell cellNibWithTableView:tableView];
        cell.indexPath = indexPath;
        cell.delegate = self;
        cell.collectShow = NO;
        HomeModel *model = self.dataMuta[indexPath.row];
        cell.homeModel = model;
        return cell;
    }else {
        ServiceCell *cell = [ServiceCell cellNibWithTableView:tableView];
        ServiceModel *model = self.dataMuta[indexPath.row];
        cell.serviceModel = model;
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 144;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     if ([self.dataMuta[indexPath.row] isKindOfClass:[HomeModel class]]) {
         HomeModel *model = self.dataMuta[indexPath.row];
         DemandTheHallContentVC *vc = [[DemandTheHallContentVC alloc]init];
         vc.returnValueBlock = ^(NSInteger selected) {
             model.collectStatus = selected;
             [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
         };
         vc.homeModel = model;
         [self.navigationController pushViewController:vc animated:YES];
     }else {
         ServiceModel *model = self.dataMuta[indexPath.row];
         ServiceContentTabVC *vc = [[ServiceContentTabVC alloc]init];
         vc.returnValueBlock = ^(NSInteger selected) {
             model.collectStatus = selected;
             [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
         };
         vc.model = model;
         [self.navigationController pushViewController:vc animated:YES];
     }

}
#pragma mark-代理:点击 全部,需求,服务
- (void)functionHeadView:(FunctionHeadView *)functionHeadView withBtn:(MCButton *)btn
{
    if (btn.tag -1 == 0) {
        [[NSNotificationCenter defaultCenter]removeObserver:self];
    }
    [self.scrollView setContentOffset:CGPointMake(kVWidth*(btn.tag-1), 0) animated:NO];
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x/kVWidth;
    if (index == 1) {
        self.headView.frame = CGRectMake(0, 0, kVWidth, 90);
    }
    XLog(@"index:%ld",index);
    MCButton *mcBtn = (MCButton *)[self.headView viewWithTag:index+1];
    [self.headView clickBtn:mcBtn];
}
#pragma mark-代理:显示联系人
-(void)demandCell:(DemandCell *)demandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    
    self.indexPath = indexPath;
    self.checkBtn = clickBtn;
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken],
                      };
        XLog(@"self.dict:%@",self.dict);
        [CustomeManager POSTCheckTokenWithURLIndex:2 parameters:self.dict success:^(NSDictionary *dict) {
            
        } failure:^(NSError *error) {
        }];
        
    }
}
#pragma mark-代理:checkToken成功
-(void)checkTokenFunction:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    XLog(@"self.dataMuta[self.indexPath.row]:%@",self.dataMuta[self.indexPath.row]);
    NSInteger status = [[info.userInfo objectForKey:@"status"] integerValue];
    if (status == 200) {
        if ([self.dataMuta[self.indexPath.row] isKindOfClass:[HomeModel class]]) {
            HomeModel *model = self.dataMuta[self.indexPath.row];
            model.show = self.checkBtn.selected;
            XLog(@"model.show:%d",model.show);
            [self.tableView reloadRowsAtIndexPaths:@[self.indexPath] withRowAnimation:UITableViewRowAnimationNone];
            
        }else {
           
        }
    }else {
        
    }
  
}
-(void)checkTokenError:(NSNotification *)info
{
    XLog(@"fuctionVC");
//    [LogOutAccount presentOutAccount];
//    [UIAlertViewWarningAccount showWarningAccount];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
//-(void)changeInternet:(NSNotification *)info
//{
//    NSString *changeInternet = [info.userInfo objectForKey:@"changeInternet"];
//    if ([changeInternet integerValue] == 0) {
//        [self.footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerNoInternet"]
//                     forState:MJRefreshStateNoMoreData];
//    }
//}

@end
